import React, { Component } from "react";
import { withRouter } from "react-router-dom";
import { observer} from 'mobx-react';
import { Icon } from 'weaver-mobile';
import { MapPage } from "weaver-mobile-page";
import classnames from 'classnames';

@withRouter
@observer
export default class MapView extends Component {
    amapEvents = {
        created: instance => {
            const {store: {mapUtil}} = this.props;
            mapUtil.mapInstance = instance;
            this.relocation();
        }
    }

    initEndCallback = () => {
        const {store: {mapUtil}} = this.props;
        mapUtil.mapInited = true;
        this.relocation();
    }

    relocation = () => {
        const {store} = this.props;
        store.getLocationInfo(this.draw);
    }

    draw = () => {
        const {store} = this.props;
        const {hasLocationInfo, currentPosition, mapUtil} = store;
        const {isAmap, clearMapData, addMarker, setCenter} = mapUtil;
        //清理地图数据
        clearMapData();
        const offset = isAmap ? new window.AMap.Pixel(-17, -34) : null;
        //添加marker
        hasLocationInfo && addMarker(currentPosition, null, offset) && setCenter(currentPosition);
    }

    render(){
        const {store} = this.props;
        const {mapUtil} = store;
        const {mapStore, isAmap, isGoogleMap, onMapTypeChangeHandle} = mapUtil;
        const mapProps = {store: mapStore, showIntroduction: false, onMapSwitch: type => onMapTypeChangeHandle(type)};
        const relocationClassName = classnames({
            'relocate': true,
            'relocate-google': !isAmap
        })
        if(isAmap){
            Object.assign(mapProps, {
                plugins: [],
                events: this.amapEvents,
                dragEnable: false,
                children: (
                    <div key='amap' className={relocationClassName} onClick={this.relocation}>
                        <Icon className='icon' type='positioning' color='#999' size='ms'/>
                    </div>
                )
            })
        }else if(isGoogleMap){
            Object.assign(mapProps, {
                initEndCallback: this.initEndCallback,
                center: [0, 0],
                needInitMarker: false,
                intiGoogleMapParams: {
                    draggable: false,
                    fullscreenControl: false
                }
            })
        }
        
        return (
            <div className='mapView'>
                <MapPage {...mapProps} />
                {
                    isGoogleMap && 
                    <div key='google' className={relocationClassName} onClick={this.relocation}>
                        <Icon className='icon' type='positioning' color='#999' size='ms'/>
                    </div>
                }
            </div>
        )
    }
}